<?php

namespace common\lib;

use Yii;

class Weixin extends yii\base\Component{

    public $appid;
    public $secret;
    private $accessToken;
    public $apis;
    
    public function init() {
        parent::init();
        $this->getAccessToken();
    }


    /**
     * 取得AccessToken
     */
    private function getAccessToken(){
        $redisKey = 'restful_access_token';
        $token = Yii::$app->redis->get($redisKey);
        if(empty($token)){
            $api = str_replace(['{APPID}', '{SECRET}'], [$this->appid, $this->secret], $this->apis['get_access_token']);
            $data = (array)json_decode(file_get_contents($api));
            $token = $data['access_token'];
            Yii::$app->redis->setex('restful_access_token', $data['expires_in'], $data['access_token']);
        }
        $this->accessToken = $token;
    }

    /**
     * 发送模板消息
     * @param  array  $data [description]
     * @return [type]       [description]
     * 
     * {
           "touser":"OPENID",
           "template_id":"ngqIpbwh8bUfcSsECmogfXcV14J0tQlEpBO27izEYtY",
           "url":"http://weixin.qq.com/download",  
           "miniprogram":{
             "appid":"xiaochengxuappid12345",
             "pagepath":"index?foo=bar"
           },          
           "data":{
                   "first": {
                       "value":"恭喜你购买成功！",
                       "color":"#173177"
                   },
                   "keyword1":{
                       "value":"巧克力",
                       "color":"#173177"
                   },
                   "keyword2": {
                       "value":"39.8元",
                       "color":"#173177"
                   },
                   "keyword3": {
                       "value":"2014年9月22日",
                       "color":"#173177"
                   },
                   "remark":{
                       "value":"欢迎再次购买！",
                       "color":"#173177"
                   }
           }
       }
     */
    public function sendMessage($data = []){
        if (empty($data) || !is_array($data)) {
            return false;
        }else{
            $api = str_replace('{ACCESS_TOKEN}', $this->accessToken, $this->apis['send_template_msg']);
            $res = $this->http_request($api, $data);
            return json_decode($res, true);
        }
    }

    /**
     * [http_request description]
     * @param  [type] $url   [description]
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function http_request($api, $data = []){
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => $api,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => array("Content-Type: application/json"),
        ));
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;

    }
}
